/*
 * Copyright (C) 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qjc.controller;

import com.qjc.feign.AccountService;
import com.qjc.feign.OrderService;
import com.qjc.feign.StorageService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName: BusinessController
 * @Description: 调用各个服务来测试分布式事务
 * @Author: qiaojiacheng
 * @Date: 2021/4/13 4:53 下午
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
@Slf4j
public class BusinessController {

    private static final String SUCCESS = "SUCCESS";
    private static final String FAIL = "FAIL";
    /**
     * 用户id
     */
    private static final String USER_ID = "1";
    /**
     * 商品代码
     */
    private static final String COMMODITY_CODE = "SEATA00001";
    /**
     * 订单价格
     */
    private static final int ORDER_MONEY = 1;
    @Resource
    OrderService orderService;
    @Resource
    StorageService storageService;
    @Resource
    AccountService accountService;

    /**
     * 分布式事务控制
     *
     * @author qiaojiacheng
     * @date 2021/4/13 4:55 下午
     */
    @GlobalTransactional(timeoutMills = 300000)
    @RequestMapping(value = "/test/seata", method = RequestMethod.GET, produces = "application/json")
    public String testSeata() {
        log.info("商品库存减1");
        String result = storageService.storage(COMMODITY_CODE);
        if (!SUCCESS.equals(result)) {
            throw new RuntimeException();
        }
        log.info("保存订单信息");
        result = orderService.order(USER_ID, COMMODITY_CODE, ORDER_MONEY);
        if (!SUCCESS.equals(result)) {
            throw new RuntimeException();
        }
        log.info("更新账户余额");
        result = accountService.updateMoney(USER_ID, ORDER_MONEY);

        if (!SUCCESS.equals(result)) {
            throw new RuntimeException();
        }
        // 出现异常，前面的调用都会回滚
        int a = 1 / 0;

        return SUCCESS;

    }

}
